// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.

// Code generated by "make store-layers"
// DO NOT EDIT

package opentracinglayer

import (
	"context"

	"github.com/mattermost/mattermost-server/v5/model"
	"github.com/mattermost/mattermost-server/v5/services/tracing"
	"github.com/mattermost/mattermost-server/v5/store"
	"github.com/opentracing/opentracing-go/ext"
	spanlog "github.com/opentracing/opentracing-go/log"
)

type {{.Name}} struct {
	store.Store
{{range $index, $element := .SubStores}}	{{$index}}Store store.{{$index}}Store
{{end}}
}

{{range $index, $element := .SubStores}}func (s *{{$.Name}}) {{$index}}() store.{{$index}}Store {
	return s.{{$index}}Store
}

{{end}}

{{range $index, $element := .SubStores}}type {{$.Name}}{{$index}}Store struct {
	store.{{$index}}Store
	Root *{{$.Name}}
}

{{end}}

{{range $substoreName, $substore := .SubStores}}
{{range $index, $element := $substore.Methods}}
func (s *{{$.Name}}{{$substoreName}}Store) {{$index}}({{$element.Params | joinParamsWithType}}) {{$element.Results | joinResultsForSignature}} {
	origCtx := s.Root.Store.Context()
	span, newCtx := tracing.StartSpanWithParentByContext(s.Root.Store.Context(), "{{$substoreName}}Store.{{$index}}")
	s.Root.Store.SetContext(newCtx)
	defer func(){
		s.Root.Store.SetContext(origCtx)
	}()
	{{range $paramName, $param := $element.Params}}
		{{if index $element.ParamsToTrace $param.Name }}
			span.SetTag("{{$param.Name}}", {{$param.Name}})
		{{end}}
	{{end}}
	defer span.Finish()
	{{- if $element.Results | len | eq 0}}
	s.{{$substoreName}}Store.{{$index}}({{$element.Params | joinParams}})
	{{else}}
		{{$element.Results | genResultsVars}} := s.{{$substoreName}}Store.{{$index}}({{$element.Params | joinParams}})
		{{- if $element.Results | errorPresent }}
			if {{$element.Results | errorVar}} != nil {
				span.LogFields(spanlog.Error({{$element.Results | errorVar}}))
				ext.Error.Set(span, true)
			}
		{{end}}	
		return {{ $element.Results | genResultsVars -}}
	{{end}}
}
{{end}}
{{end}}

{{range $index, $element := .Methods}}
func (s *{{$.Name}}) {{$index}}({{$element.Params | joinParamsWithType}}) {{$element.Results | joinResultsForSignature}} {
	{{if $element.Results | len | eq 0}}s.Store.{{$index}}({{$element.Params | joinParams}})
	{{else}}return s.Store.{{$index}}({{$element.Params | joinParams}})
	{{end}}}
{{end}}

func New(childStore store.Store, ctx context.Context) *{{.Name}} {
	newStore := {{.Name}}{
		Store: childStore,
	}
	{{range $substoreName, $substore := .SubStores}}
	newStore.{{$substoreName}}Store = &{{$.Name}}{{$substoreName}}Store{{"{"}}{{$substoreName}}Store: childStore.{{$substoreName}}(), Root: &newStore}{{end}}
	return &newStore
}
